package com.ruoyi.fun.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcProductSku;
import com.ruoyi.fun.service.IEcProductSkuService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品SKUController
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@RestController
@RequestMapping("/fun/sku")
public class EcProductSkuController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(EcProductSkuController.class);
    
    @Autowired
    private IEcProductSkuService ecProductSkuService;

    /**
     * 查询商品SKU列表
     */
    @PreAuthorize("@ss.hasPermi('fun:sku:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcProductSku ecProductSku)
    {
        startPage();
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        System.out.println("[DEBUG] EcProductSkuController.list - getOrgId()返回值: " + orgId);
        ecProductSku.setOrgId(orgId);
        System.out.println("[DEBUG] EcProductSkuController.list - 设置后的ecProductSku.orgId: " + ecProductSku.getOrgId());
        List<EcProductSku> list = ecProductSkuService.selectEcProductSkuList(ecProductSku);
        System.out.println("[DEBUG] EcProductSkuController.list - 最终返回的数据条数: " + list.size());
        return getDataTable(list);
    }

    /**
     * 导出商品SKU列表
     */
    @PreAuthorize("@ss.hasPermi('fun:sku:export')")
    @Log(title = "商品SKU", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcProductSku ecProductSku)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        ecProductSku.setOrgId(orgId);
        List<EcProductSku> list = ecProductSkuService.selectEcProductSkuList(ecProductSku);
        ExcelUtil<EcProductSku> util = new ExcelUtil<EcProductSku>(EcProductSku.class);
        util.exportExcel(response, list, "商品SKU数据");
    }

    /**
     * 更新SKU销量
     */
    @Log(title = "更新SKU销量", businessType = BusinessType.UPDATE)
    @PostMapping("/updateSaleCount/{skuId}")
    public AjaxResult updateSkuSaleCount(@PathVariable("skuId") Long skuId, @RequestBody Map<String, Object> params)
    {
        try {
            Integer increment = (Integer) params.get("increment");
            Long orgId = null;
            Object orgIdObj = params.get("orgId");
            if (orgIdObj instanceof String) {
                orgId = Long.parseLong((String) orgIdObj);
            } else if (orgIdObj instanceof Long) {
                orgId = (Long) orgIdObj;
            } else if (orgIdObj instanceof Integer) {
                orgId = ((Integer) orgIdObj).longValue();
            }
            
            if (increment == null) {
                increment = 1; // 默认增量为1
            }
            if (orgId == null) {
                orgId = getOrgId(); // 使用当前用户的组织ID
            }
            
            System.out.println("=== SKU销量更新接口调用 ===");
            System.out.println("SKU ID: " + skuId);
            System.out.println("增量: " + increment);
            System.out.println("组织ID: " + orgId);
            
            int result = ecProductSkuService.updateSkuSaleCount(skuId, increment, orgId);
            
            if (result > 0) {
                System.out.println("SKU销量更新成功");
                return AjaxResult.success("SKU销量更新成功");
            } else {
                System.out.println("SKU销量更新失败");
                return AjaxResult.error("SKU销量更新失败");
            }
        } catch (Exception e) {
            System.out.println("更新SKU销量异常: " + e.getMessage());
            logger.error("更新SKU销量失败：" + e.getMessage(), e);
            return AjaxResult.error("更新SKU销量失败：" + e.getMessage());
        }
    }

    /**
     * 导入商品SKU数据
     */
    @Log(title = "商品SKU", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam(value = "updateSupport", defaultValue = "false") boolean updateSupport) throws Exception
    {
        ExcelUtil<EcProductSku> util = new ExcelUtil<EcProductSku>(EcProductSku.class);
        List<EcProductSku> skuList = util.importExcel(file.getInputStream());
        
        // 预处理Excel解析后的数据，设置默认值
        for (EcProductSku sku : skuList) {
            if (sku.getWeight() == null) {
                sku.setWeight(new java.math.BigDecimal("0.00"));
            }
            if (sku.getVolume() == null) {
                sku.setVolume(new java.math.BigDecimal("0.00"));
            }
            if (sku.getImage() == null || sku.getImage().trim().isEmpty()) {
                sku.setImage("");
            }
            if (sku.getSaleCount() == null) {
                sku.setSaleCount(0L);
            }
            if (sku.getStatus() == null || sku.getStatus().trim().isEmpty()) {
                sku.setStatus("0");
            }
            if (sku.getLowStock() == null) {
                sku.setLowStock(0L);
            }
            if (sku.getOriginalPrice() == null) {
                sku.setOriginalPrice(sku.getPrice());
            }
            if (sku.getCostPrice() == null) {
                sku.setCostPrice(new java.math.BigDecimal("0.00"));
            }
            if (sku.getSpecInfo() == null || sku.getSpecInfo().trim().isEmpty()) {
                sku.setSpecInfo("");
            }
        }
        
        String operName = getUsername();
        Long orgId = getOrgId();
        String message = ecProductSkuService.importSku(skuList, updateSupport, operName, orgId);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<EcProductSku> util = new ExcelUtil<EcProductSku>(EcProductSku.class);
        util.importTemplateExcel(response, "商品SKU数据");
    }

    /**
     * 获取商品SKU详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:sku:query')")
    @GetMapping(value = "/{skuId}")
    public AjaxResult getInfo(@PathVariable("skuId") Long skuId)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        return success(ecProductSkuService.selectEcProductSkuBySkuIdAndOrgId(skuId, orgId));
    }

    /**
     * 新增商品SKU
     */
    @PreAuthorize("@ss.hasPermi('fun:sku:add')")
    @Log(title = "商品SKU", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcProductSku ecProductSku)
    {
        ecProductSku.setOrgId(getOrgId());
        return toAjax(ecProductSkuService.insertEcProductSku(ecProductSku));
    }

    /**
     * 修改商品SKU
     */
    @PreAuthorize("@ss.hasPermi('fun:sku:edit')")
    @Log(title = "商品SKU", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcProductSku ecProductSku)
    {
        return toAjax(ecProductSkuService.updateEcProductSku(ecProductSku));
    }

    /**
     * 删除商品SKU
     */
    @PreAuthorize("@ss.hasPermi('fun:sku:remove')")
    @Log(title = "商品SKU", businessType = BusinessType.DELETE)
	@DeleteMapping("/{skuIds}")
    public AjaxResult remove(@PathVariable Long[] skuIds)
    {
        return toAjax(ecProductSkuService.deleteEcProductSkuBySkuIds(skuIds));
    }
    /**
     * 根据skuId和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:ecproductsku:query')")
    @GetMapping(value = "/{skuId}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("skuId") Long skuId, @PathVariable("orgId") Long orgId)
    {
        return success(ecProductSkuService.selectEcProductSkuBySkuIdAndOrgId(skuId, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('fun:ecproductsku:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcProductSku ecProductsku = new EcProductSku();
        List<EcProductSku> list = ecProductSkuService.selectEcProductSkuListByOrgId(ecProductsku, orgId);
        return getDataTable(list);
    }


}

